package cat.joronya.supermanager.europeo.team;

import java.util.Hashtable;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import cat.joronya.supermanager.europeo.DatabaseHelper;
import cat.joronya.supermanager.europeo.Supermanager;
import cat.joronya.supermanager.europeo.Supermanager.MyTeamDetail;

/**
 * Provides access to a database of my team details.
 */
public class MyTeamDetailProvider extends ContentProvider 
{
	// pel Log
	private static final String TAG = "supermanager";
	
	public static final int MY_TEAM_DETAIL = 1;
	public static final int MY_TEAM_DETAIL_ID = 2;
	
	public static final UriMatcher uriMatcher;
	static {
		uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		uriMatcher.addURI(Supermanager.MyTeamDetail.AUTHORITY, "myteamdetail", MY_TEAM_DETAIL);
		uriMatcher.addURI(Supermanager.MyTeamDetail.AUTHORITY, "myteamdetail/#", MY_TEAM_DETAIL_ID);
	}

    private DatabaseHelper mOpenHelper;
    
    @Override
    public boolean onCreate() {
        mOpenHelper = new DatabaseHelper(getContext());
        return true;
    }
    
	@Override
	public int delete(Uri uri, String where, String[] whereArgs) 
	{
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int count;
		switch (uriMatcher.match(uri)) {
		case MY_TEAM_DETAIL:
			count = db.delete(DatabaseHelper.MY_TEAM_DETAIL_TABLE_NAME, where, whereArgs);
			break;

		case MY_TEAM_DETAIL_ID:
			String mtdId = uri.getPathSegments().get(1);
			count = db.delete(DatabaseHelper.MY_TEAM_DETAIL_TABLE_NAME, MyTeamDetail._ID + "=" + mtdId
					+ (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
			break;

		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}

		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	@Override
	public String getType(Uri uri) 
	{
		switch (uriMatcher.match(uri)) {
        case MY_TEAM_DETAIL:
            return Supermanager.MyTeamDetail.CONTENT_TYPE;

        case MY_TEAM_DETAIL_ID:
            return Supermanager.MyTeamDetail.CONTENT_ITEM_TYPE;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
	}

	@Override
	public Uri insert(Uri uri, ContentValues initialValues) 
	{
		// Validate the requested uri
        if (uriMatcher.match(uri) != MY_TEAM_DETAIL) {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        ContentValues values;
        if (initialValues != null) {
            values = new ContentValues(initialValues);
        } else {
            values = new ContentValues();
        }
        
        Long now = Long.valueOf(System.currentTimeMillis());

        // afegim el modified si no el tenim als values
        if( values.containsKey(Supermanager.MyTeamDetail.MODIFIED_DATE) == false )
        {
            values.put(Supermanager.MyTeamDetail.MODIFIED_DATE, now);
        }

		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        long rowId = db.insert(DatabaseHelper.MY_TEAM_DETAIL_TABLE_NAME, "", values);
        if (rowId > 0) {
            Uri insertUri = ContentUris.withAppendedId(Supermanager.MyTeamDetail.CONTENT_URI, rowId);
            getContext().getContentResolver().notifyChange(insertUri, null);
            return insertUri;
        }

        throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) 
	{
		SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
		sqlBuilder.setTables(DatabaseHelper.MY_TEAM_DETAIL_TABLE_NAME);

		// recuperant una PL concreta
		if( uriMatcher.match(uri) == MY_TEAM_DETAIL_ID )
			sqlBuilder.appendWhere(MyTeamDetail._ID + " = " + uri.getPathSegments().get(1));                

		// If no sort order is specified use the default
        String orderBy;
        if (TextUtils.isEmpty(sortOrder)) {
            orderBy = MyTeamDetail.DEFAULT_SORT_ORDER;
        } else {
            orderBy = sortOrder;
        }
        
        // Get the database and run the query
        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        
        Cursor c = sqlBuilder.query(
			db, 
			projection, 
			selection, 
			selectionArgs, 
			null, 
			null, 
			orderBy);

		// register to watch a content URI for changes
		c.setNotificationUri(getContext().getContentResolver(), uri);
		return c;
	}

	@Override
	public int update(Uri uri, ContentValues values, String where, String[] whereArgs) 
	{
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int count;
		switch (uriMatcher.match(uri)) {
		case MY_TEAM_DETAIL:
			count = db.update(DatabaseHelper.MY_TEAM_DETAIL_TABLE_NAME, values, where, whereArgs);
			break;

		case MY_TEAM_DETAIL_ID:
			String noteId = uri.getPathSegments().get(1);
			count = db.update(DatabaseHelper.MY_TEAM_DETAIL_TABLE_NAME, values, MyTeamDetail._ID + "=" + noteId
					+ (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
			break;

		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}

		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	/**
	 * Returns the totals for a team by day. Agregates all values and its averages.
	 * @param context
	 * @param idEqu
	 * @param day
	 * @return the hashtable of total values.
	 */
	public Hashtable<String, Float> getTotals(Context context, int idEqu, long day) 
	{
		SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
		
		// nomes ens interessen valors dels jugadors de l'equip per fer totals
		sqlBuilder.setTables(DatabaseHelper.MY_TEAM_DETAIL_TABLE_NAME);

		sqlBuilder.appendWhere(
				DatabaseHelper.MY_TEAM_DETAIL_TABLE_NAME+"."+MyTeamDetail.ID_EQU + " = " + idEqu+" AND "+
				DatabaseHelper.MY_TEAM_DETAIL_TABLE_NAME+"."+MyTeamDetail.DAY + " = " + day
			);

		String[] PROJECTION = new String[]{
			"SUM("+DatabaseHelper.MY_TEAM_DETAIL_TABLE_NAME+"."+Supermanager.MyTeamDetail.PRICE+") AS PRICE",					// 0
			"SUM("+DatabaseHelper.MY_TEAM_DETAIL_TABLE_NAME+"."+Supermanager.MyTeamDetail.COST+") AS COST",							// 1
			"SUM("+DatabaseHelper.MY_TEAM_DETAIL_TABLE_NAME+"."+Supermanager.MyTeamDetail.RATING_AVERAGE+") AS RATING_AVERAGE",		// 2
			"SUM("+DatabaseHelper.MY_TEAM_DETAIL_TABLE_NAME+"."+Supermanager.MyTeamDetail.POINTS_AVERAGE+") AS POINTS_AVERAGE",		// 3
			"SUM("+DatabaseHelper.MY_TEAM_DETAIL_TABLE_NAME+"."+Supermanager.MyTeamDetail.REBOUNDS_AVERAGE+") AS REBOUNDS_AVERAGE",	// 4
			"SUM("+DatabaseHelper.MY_TEAM_DETAIL_TABLE_NAME+"."+Supermanager.MyTeamDetail.THREE_AVERAGE+") AS THREE_AVERAGE",		// 5
			"SUM("+DatabaseHelper.MY_TEAM_DETAIL_TABLE_NAME+"."+Supermanager.MyTeamDetail.ASSISTS_AVERAGE+") AS ASSISTS_AVERAGE",	// 6
			"SUM("+DatabaseHelper.MY_TEAM_DETAIL_TABLE_NAME+"."+Supermanager.MyTeamDetail.RATING+") AS RATING",						// 7
			"SUM("+DatabaseHelper.MY_TEAM_DETAIL_TABLE_NAME+"."+Supermanager.MyTeamDetail.POINTS+") AS POINTS",						// 8
			"SUM("+DatabaseHelper.MY_TEAM_DETAIL_TABLE_NAME+"."+Supermanager.MyTeamDetail.REBOUNDS+") AS REBOUNDS",					// 9
			"SUM("+DatabaseHelper.MY_TEAM_DETAIL_TABLE_NAME+"."+Supermanager.MyTeamDetail.THREE+") AS THREE",						// 10
			"SUM("+DatabaseHelper.MY_TEAM_DETAIL_TABLE_NAME+"."+Supermanager.MyTeamDetail.ASSISTS+") AS ASSISTS",					// 11
			DatabaseHelper.MY_TEAM_DETAIL_TABLE_NAME+"."+Supermanager.MyTeamDetail.ID_EQU											// 12
		};
		
		// Get the database and run the query
		mOpenHelper = new DatabaseHelper(context);
        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        
        Cursor c = sqlBuilder.query(
			db, 
			PROJECTION, 
			null, 
			null, 
			DatabaseHelper.MY_TEAM_DETAIL_TABLE_NAME+"."+Supermanager.MyTeamDetail.ID_EQU, 
			null, 
			null);
        
        // recorre cursor i assignar els valors de la unica row a totals
        Hashtable<String, Float> totals = new Hashtable<String, Float>();
        if( c.moveToFirst() )
		{
			totals.put("PRICE", c.getFloat(0));
			totals.put("COST", c.getFloat(1));
			totals.put("RATING_AVERAGE", c.getFloat(2));
			totals.put("POINTS_AVERAGE", c.getFloat(3));
			totals.put("REBOUNDS_AVERAGE", c.getFloat(4));
			totals.put("THREE_AVERAGE", c.getFloat(5));
			totals.put("ASSISTS_AVERAGE", c.getFloat(6));
			totals.put("RATING", c.getFloat(7));
			// aquest son int, fa be la cast-conversio
			totals.put("POINTS", c.getFloat(8));
			totals.put("REBOUNDS", c.getFloat(9));
			totals.put("THREE", c.getFloat(10));
			totals.put("ASSISTS", c.getFloat(11));
		}
        if( c.moveToNext() )
        {
        	Log.d(TAG,"tenim mes d'una fila! error!");
        }
        
        c.close();
        
		return totals;
	}
	
	/**
	 * Close the helper database.
	 */
	public void closeHelper()
	{
		mOpenHelper.close();
	}
}
